package com.baohua.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Member;

import com.baohua.service.MemberService;


@Controller
@RequestMapping("/member")
public class MemberController  {

	private static final Logger logger = LoggerFactory.getLogger(StaffController.class);
	
	private MemberService memberService;

	public MemberService getMemberService() {
		return memberService;
	}
	@Resource(name="memberService")
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	
	/**
	 * 跳转至会员信息页面
	 * @throws BaohuaSystemException 
	 * 
	 * */
	@RequestMapping("/index")
	public String index() throws BaohuaSystemException {
		return "member";
	}
	
	
	/**
	 * 根据条件查询员工列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/conditionsList")
	public @ResponseBody Map queryListbyCondition(HttpServletRequest request){
		
		
		
		StringBuffer sqlCount = new StringBuffer("select count(*) from Member m where 1=1");
		StringBuffer sql = new StringBuffer("from Member m where 1=1");
//		int page = Integer.parseInt(request.getParameter("page"));
//		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		
		String memberNo = request.getParameter("memberNo");
		String memberName = request.getParameter("memberName");
		String registrationTime = request.getParameter("registrationTime");
		String birth = request.getParameter("birth");
		
		if(!StringUtils.isEmpty(memberNo)) {
			sql.append(" and m.memberNo = '" + memberNo + "'");
			sqlCount.append(" and m.memberNo = '" + memberNo + "'");
		}
		if(!StringUtils.isEmpty(memberName)) {
			sql.append(" and m.memberName = '" + memberName + "'");
			sqlCount.append(" and m.memberName = '" + memberName + "'");
		}
		if(!StringUtils.isEmpty(registrationTime)) {
			sql.append(" and m.registrationTime = '" + registrationTime + "'");
			sqlCount.append(" and m.registrationTime = '" + registrationTime + "'");
		}
		if(!StringUtils.isEmpty(birth)) {
			sql.append(" and m.birth = '" + birth + "'");
			sqlCount.append(" and m.birth = '" + birth + "'");
		}

		
		System.out.println(sql.toString());
		System.out.println(sqlCount.toString());
		
		//分页显示
		List<Member> list = memberService.queryMember(sql.toString(),0, 10);
//	    List<Member> list = memberService.queryMember(sql.toString(),(page-1)*pageSize, pageSize);
		long count = memberService.countMember(sqlCount.toString());
		Map map = new HashMap();
		map.put("Rows", list);
		map.put("Total", count);
		return map;
	}
	
	/**
	 * 增加员工信息
	 * @param member
	 * @param request
	 * @return
	 * @throws BaohuaSystemException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String addMember(Member member, HttpServletRequest request) throws BaohuaSystemException, ParseException {
		
		Date registrationTime = null;
		Date birth = null;
		
		String rtDate = request.getParameter("add_registrationTime");
		String bDate = request.getParameter("add_birth");		
		
	    SimpleDateFormat rt = new SimpleDateFormat("yyyy-MM-dd");	    
    	if(!StringUtils.isBlank(rtDate)){
    		registrationTime = rt.parse(rtDate);
    	}
    	
    	SimpleDateFormat b = new SimpleDateFormat("yyyy-MM-dd");
    	if(!StringUtils.isBlank(bDate)){
    		birth = b.parse(bDate);
    	}
    	
    	
    	member.setRegistrationTime(registrationTime);
    	member.setBirth(birth);
    	
		memberService.addMember(member);
	    	
		return "redirect:/member/index";
	}
	
	/**
	 * 修改员工信息
	 * @param member
	 * @param request
	 * @return
	 * @throws BaohuaSystemException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String updateMember(Member member, HttpServletRequest request) throws BaohuaSystemException, ParseException{

		String registrationTime = request.getParameter("update_registrationTime");
		String birth = request.getParameter("update_birth");
//		String  leaveDate1 = request.getParameter("update_leaveDate");
		String update_memberId = request.getParameter("update_memberId");
		//1、将传过来的值数据转换,加入Staff中
		member.setMemberId(Integer.parseInt(update_memberId));
					
					

		 SimpleDateFormat rtDate = new SimpleDateFormat("yyyy-MM-dd");
		    
	    	if(registrationTime!=null && (!"".equals(registrationTime.trim()))){
	    		member.setRegistrationTime(rtDate.parse(registrationTime));
	    	}
	    	
		SimpleDateFormat bDate = new SimpleDateFormat("yyyy-MM-dd");
				    
			    	if(birth!=null && (!"".equals(birth.trim()))){
			    		member.setBirth(bDate.parse(birth));
			    	}

			memberService.updateMember(member);

		return "redirect:/member/index";
	}
	
	/**
	 * 异步删除员工信息
	 * @param rowsNum
	 * @return
	 */
	@RequestMapping(value="/del/{rowsNum}", method=RequestMethod.GET)
	public @ResponseBody String delMember(@PathVariable String rowsNum) {
// 		String s = request.getParameter("rowsNum");
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			//jackson类型转换
			String[] memberIds = objectMapper.readValue(rowsNum, String[].class);
			for(String memberId : memberIds) {
				memberService.delMember(Integer.parseInt(memberId));
			}
		} catch (JsonParseException e) {
			logger.info(e.getMessage());
			return "{message:systemerror}";
		} catch (JsonMappingException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		} catch (IOException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		} catch (NumberFormatException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		} catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			return "{message:'error'}";
		}
		return "{message : 'success'}";
	}
	
	
}


